package service

import (
	"errors"
	"github.com/gccai/write_helper/model"
	"github.com/gccai/write_helper/repository"
	"github.com/gccai/write_helper/utils"
)

type ChapterService struct {
	Repo repository.ChapterRepositoryInterface
}

type ChapterServiceInterface interface {
	Add(chapter *model.Chapter) (*model.Chapter, error)
	Delete(chapter *model.Chapter) (bool, error)
	Edit(chapter *model.Chapter) *model.Chapter
	GetChapterCount(chapter *model.Chapter) (int64, error)
	GetChapterContent(chapter *model.Chapter) (*model.Chapter, error)
	GetChapters(chapter *model.Chapter) ([]*model.Chapter, error)
	Exist(num string) (bool, error)
}

func (c ChapterService) Add(chapter *model.Chapter) (*model.Chapter, error) {
	if chapter.ChapterContent == "" || chapter.ChapterName == "" || chapter.ChapterId == "" {
		return nil, errors.New("service层检测到必要信息为空")
	}
	count, err := c.GetChapterCount(chapter)
	if err != nil {
		return nil, errors.New("添加失败")
	}
	count++
	myUUID, err := utils.GetUUID(string(count))
	chapter.ChapterId = myUUID
	return c.Repo.Add(chapter)

}

func (c ChapterService) Delete(chapter *model.Chapter) (bool, error) {
	if chapter.ChapterId == "" {
		return false, errors.New("service层检测到userid 为空")
	}
	return c.Repo.Delete(chapter)
}

func (c ChapterService) Edit(chapter *model.Chapter) *model.Chapter {
	if chapter.ChapterId == "" {
		return nil
	}
	return c.Repo.Edit(chapter)
}

func (c ChapterService) GetChapterCount(chapter *model.Chapter) (int64, error) {
	if chapter.UserId == "" || chapter.BookName == "" || chapter.ChapterId == "" {
		return -1, errors.New("参数错误")
	}
	return c.Repo.GetChapterCount(chapter)
}

func (c ChapterService) GetChapterContent(chapter *model.Chapter) (*model.Chapter, error) {
	if chapter.ChapterId == "" || chapter.BookName == "" || chapter.UserId == "" {
		return nil, errors.New("参数错误")
	}
	return c.Repo.GetChapterContent(chapter)
}

func (c ChapterService) GetChapters(chapter *model.Chapter) ([]*model.Chapter, error) {
	if chapter.UserId == "" || chapter.BookName == "" {
		return nil, errors.New("参数错误")
	}
	return c.Repo.GetChapters(chapter)
}

func (c ChapterService) Exist(num string) (bool, error) {
	if num == "" {
		return false, errors.New("参数为空")
	}
	userId, err := utils.GetUUID(num)
	if err != nil {
		return false, err
	}
	return c.Repo.Exist(userId)
}
